import { action, observable, runInAction } from "mobx";
import { ILoginResponse, ISpaceInvitation } from "src/interfaces";
import { generateClientRSAKeyPair } from "../../src/utils/encrypt-utils";
import { instance, setStore } from "../utils";

export const getToken = async () => {
  return new Promise<void>((resolve) => {
    const { clientRSAPublicKey, clientRSAPrivateKey } =
      generateClientRSAKeyPair();
    setStore("priRsaKey", clientRSAPrivateKey);
    setStore("pubRsaKey", clientRSAPublicKey);
    return instance
      .post("/user/pub/rsa", { pubKey: clientRSAPublicKey })
      .then(({ data }) => data)
      .then((data: ILoginResponse) => {
        if (!data || !data.accessToken) {
          // 接口返回异常
          window.location.reload();
          return;
        }
        setStore("token", data.accessToken);
        resolve();
      });
  });
};

export class RootStore {
  @observable curChannelInfo = {
    id: "index",
    type: "index",
    name: "首页",
  };

  @observable curIndex = 0;
  @observable routerChange = +new Date();

  @observable toast = {
    duration: 2000,
  };
  @observable token = "";

  @action
  setCurChannelInfo = (val) => {
    this.curChannelInfo = val;
  };

  @action
  setRouterChange = () => {
    this.routerChange = +new Date();
  };

  @action
  setCurIndex = (val) => {
    this.curIndex = val;
  };

  /** 获取匿名token */
  @action
  getToken = () => getToken();

  @action
  setValues = <T extends Partial<keyof RootStore>>(
    states: Partial<RootStore>
  ) => {
    (Object.keys(states) as T[]).forEach((key) => {
      const newVal = states[key];
      (this as any)[key] = newVal as RootStore[T];
    });
  };
}
